package com.sbw.tinysoft.Utils.analyzer.impl;

import com.sbw.tinysoft.Utils.analyzer.DocumentAnalyzer;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析 MethodDayList 页面
 * http://super.lvmama.com/prism-web/lvmama_soa_monitor/list/provider/method/method_day_list.do?appName=visa_prod&service=com.lvmama.visa.api.service.VisaDocService&dayStr=2017-12-06
 * @Author: sangbowei
 * @Description: TODO
 * @Date: Created in  14:53 2017\12\6 0006
 **/
@Component
public class VisaMethodDayListDocumentAnalyzer implements DocumentAnalyzer {

    private String service;

    @Override
    public List<Map<String, Object>> forListMap(Document document) {
        service = null;

        List<Map<String, Object>> results = new ArrayList<>();
        if (ObjectUtils.isEmpty(document))
            return results;

        List<String> methodNameList = new ArrayList<>();
        Elements tbodyEle = document.body().getElementsByTag("tbody").get(0).children();
        tbodyEle.forEach(ele -> {
            Elements tdEle = ele.getElementsByTag("tr").get(0).getElementsByTag("td");
            if(tdEle.size()>0){
                Elements serviceTdEle = tdEle.get(1).getElementsByTag("td");
                if(StringUtils.isEmpty(service)){
                    service = serviceTdEle.text();
                }
                Elements methodTdEle = tdEle.get(2).getElementsByTag("td");
                String methodName = methodTdEle.text();
                methodNameList.add(methodName);
            }
        });

        if(!CollectionUtils.isEmpty(methodNameList)){
            Map<String, Object> result = new HashMap<>();
            result.put("service",service);
            result.put("methods",methodNameList);
            results.add(result);
        }
        return results;
    }
}
